using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;

[RequireComponent(typeof(HS_BoneFixer))]
public class HS_ClothChanger : MonoBehaviour
{
    #region Variables

    [HideInInspector]
    public HS_BoneFixer boneFixer;

    [Header("---------- Clothes Changer Properties ----------")]
    public HS_Cloth changedCloth;

    #endregion Variables

    #region Init

    public void Init()
    {
        boneFixer = GetComponent<HS_BoneFixer>();
    }

    #endregion Init

    #region Clothes State

    public void AddClothes()
    {
        // 加载衣服
        boneFixer.LoadBonesDic();
        changedCloth.LoadClothesBoneDic();

        // 更换衣服骨骼
        ChangeClothesBone(changedCloth.transform);

        // 清理衣服层级
        changedCloth.transform.SetParent(transform);
        changedCloth.transform.localEulerAngles = Vector3.zero;
        changedCloth.transform.localPosition = Vector3.zero;

        DestroyImmediate(changedCloth);

        changedCloth = null;
    }

    #endregion Clothes State

    #region Change Cloth

    private void ChangeClothesBone(Transform target)
    {
        SkinnedMeshRenderer[] targetSkins = target.GetComponentsInChildren<SkinnedMeshRenderer>();
        for (int i = 0; i < targetSkins.Length; i++)
        {
            if (targetSkins[i].rootBone != null)
            {
                //替换骨骼根节点
                Transform tf = boneFixer.GetBone(targetSkins[i].rootBone.name);
                if (targetSkins[i].rootBone == tf)
                {
                    //增加效率，如果已经替换过骨骼节点，就不需要再次替换
                    return;
                }
                else
                {
                    targetSkins[i].rootBone = tf;
                }
            }
            Transform[] tfs = new Transform[targetSkins[i].bones.Length];
            for (int j = 0; j < targetSkins[i].bones.Length; j++)
            {
                //替换所有骨骼节点
                if (null == targetSkins[i].bones[j])
                {
                    //如果骨骼节点为null
                    Debug.LogWarning(targetSkins[i].name + "  " + j);
                }
                else
                {
                    tfs[j] = boneFixer.GetBone(targetSkins[i].bones[j].name);
                }
            }
            targetSkins[i].bones = tfs;
        }
    }

    #endregion Change Cloth
}

#if UNITY_EDITOR

[CustomEditor(typeof(HS_ClothChanger))]
public class HS_ClothChanger_Editor : Editor
{
    public override void OnInspectorGUI()
    {
        DrawDefaultInspector();

        GUILayout.BeginHorizontal();

        if (GUILayout.Button("Add Clothes"))
        {
            (target as HS_ClothChanger).AddClothes();
            GUIUtility.ExitGUI();
        }

        GUILayout.EndHorizontal();
    }
}

#endif